﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XinjeMesProgram.Entities;
using XinjeMesProgram.Entities.RoleAndUser;
using XinjeMesProgram.Entities.User;

namespace PublicModelsAndEntities.Entities.Function
{
    public class XinjeCloudUserQuery
    {
        /// <summary>
        /// 数据库获取用户实例.
        /// </summary>
        /// <param name="userId">用户id.</param>
        /// <param name="userEntity">用户实例信息.</param>
        /// <returns>是否查询成功.</returns>
        public static bool GetUserEntity(string userId, out MesUserRole userEntity)
        {
            using var dbContext = new FactoryMesContext();

            userEntity = dbContext.MesUserRole.FirstOrDefault(x => x.ID == userId);
            if (userEntity != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 编辑角色的权限信息 v1.0.
        /// </summary>
        /// <param name="roleId">角色或用户信息.</param>
        /// <param name="bindInfo">绑定权限.</param>
        /// <param name="isUser">是否为用户.</param>
        /// <param name="errMsg">操作信息.</param>
        /// <returns>是否操作成功.</returns>
        public static bool EditPermission(string roleId, List<string> bindInfo, bool isUser, out string errMsg)
        {
            try
            {
                using var dbContext = new FactoryMesContext();

                // 先删除当前角色原来已分配的权限
                dbContext.Database.ExecuteSqlRaw(string.Format(
                    "DELETE FROM AuthRolePermissionMapping WHERE RoleCode= '{0}'",
                    roleId));
                dbContext.SaveChanges();

                if (bindInfo != null && bindInfo.Count > 0)
                {
                    var permissions = bindInfo.Select(x => new RolePermissionMapping
                    {
                        CreatedOn = DateTime.Now,
                        PermissionCode = x.Trim(),
                        RoleCode = roleId.Trim(),
                    });

                    dbContext.AuthRolePermissionMapping.AddRange(permissions);
                    dbContext.SaveChanges();

                    if (isUser)
                    {
                        var temp = dbContext.MesUserRole.FirstOrDefault(x => x.ID == roleId);
                        if (temp != null)
                        {
                            temp.IsDefinedPermisson = 1;
                            dbContext.SaveChanges();
                        }
                    }

                    // LogDataSQLFun.SaveUserLog(
                    //    "分配角色权限：" + payload.RoleCode,
                    //    AuthContextService.CurrentUser.UserName,
                    //    AuthContextService.CurrentUser.Guid,
                    //    AuthContextService.CurrentUser.UserContact,
                    //    "-",
                    //    AuthContextService.CurrentUser.RegGroupId);
                    errMsg = "编辑成功";
                    return true;
                }
                else
                {
                    errMsg = "编辑信息为空";
                    if (isUser)
                    {
                        var temp = dbContext.MesUserRole.FirstOrDefault(x => x.ID == roleId);
                        if (temp != null)
                        {
                            temp.IsDefinedPermisson = 0;
                            dbContext.SaveChanges();
                        }
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                // MyLogFunction.SaveOperatorLog("分配权限异常", ex.Message);
                errMsg = ex.Message;
            }

            return false;
        }

        /// <summary>
        /// 获取用户名.
        /// </summary>
        /// <param name="UserId">用户id.</param>
        /// <returns></returns>
        public static string GetUserName(string? UserId)
        {
            string Name = string.Empty;
            using (FactoryMesContext factoryMes = new FactoryMesContext())
            {
                if (!string.IsNullOrEmpty(UserId))
                {
                    var info = factoryMes.MesUserRole.FirstOrDefault(x => x.ID == UserId);
                    if (info != null)
                    {
                        Name = info.UserName;
                    }
                }
            }
            return Name;
        }
    }
}
